package com.vr.cloudpicture.util;

import java.awt.Color;

/**
 * 颜色相似度计算工具类（支持RGB/LAB/HSV空间比较）
 *
 * @author hzh
 * @date 2025/05/22
 */
public class ColorSimilarityUtils {


    // 人眼敏感度权重（红:29.7%、绿:59.3%、蓝:11%）
    private static final double[] RGB_WEIGHTS = {0.297, 0.593, 0.11};
    // 最大加权色差（255 * sum(weights)）
    private static final double MAX_WEIGHTED_DIFF = 255.0;

    private ColorSimilarityUtils() {}

    /**
     * 计算加权色差（值越大越相似,最大为1）
     * @param c1 颜色1
     * @param c2 颜色2
     * @return 加权色差值[0, 255][1](@ref)
     */
    public static double weightedColorDifference(Color c1, Color c2) {
        double rDiff = Math.abs(c1.getRed() - c2.getRed()) * RGB_WEIGHTS[0];
        double gDiff = Math.abs(c1.getGreen() - c2.getGreen()) * RGB_WEIGHTS[1];
        double bDiff = Math.abs(c1.getBlue() - c2.getBlue()) * RGB_WEIGHTS[2];
        return 1 - (rDiff + gDiff + bDiff) / MAX_WEIGHTED_DIFF;
    }
    /**
     * 计算加权色差（值越大越相似,最大为1）
     * @param hexColor1 颜色1(16进制)
     * @param hexColor2 颜色2(16进制)
     * @return 相似度(0-1之间,1完全相同)
     */
    public static double weightedColorDifference(String hexColor1, String hexColor2) {
        Color c1Color = Color.decode(hexColor1);
        Color c2Color = Color.decode(hexColor2);
        return weightedColorDifference(c1Color, c2Color);
    }

    public static void main(String[] args) {
        // 测试颜色
        Color color1 = Color.decode("#1f87e8");
        Color color2 = Color.decode("0x6f5d4a");
        Color color3 = Color.decode("0x1a2052");
        Color color4 = Color.decode("0x323636");
        double similarity1 = weightedColorDifference(color1, color2);
        double similarity2= weightedColorDifference(color1, color3);
        double similarity3= weightedColorDifference(color1, color4);
        System.out.println(similarity1);
        System.out.println(similarity2);
        System.out.println(similarity3);
    }
}